package com.exonline.front.controller.carousel;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc轮播图数据管理的C层
 * @author hbrj
 */
@WebServlet("/font/carousel")
public class CarouselServlet extends HttpServlet {

    // 轮播图类，用于处理管理轮播图相关业务逻辑
    CarouselService service = new CarouselService();

    // 使用Jackson库进行JSON格式的响应输出
    ObjectMapper mapper = new ObjectMapper();

    /**
     * @desc 获取轮播图资源,对轮播图相关资源进行管理
     * @param req  客户端请求
     * @param resp 服务端响应
     * @throws ServletException 如果请求处理过程中发生错误
     * @throws IOException 如果响应过程中发生I/O错误
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取轮播图数据
            List<Map<String, Object>> carouselData = service.getCarouselData();

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", 200);
            resultMap.put("msg", "轮播图数据获取成功");
            resultMap.put("data", carouselData);

            // 设置响应头，指定返回的数据格式为JSON
            resp.setContentType("application/json;charset=UTF-8");
            // 获取输出流，将结果转换为JSON格式并写入响应流
            PrintWriter writer = resp.getWriter();
            mapper.writeValue(writer, resultMap);
        } catch (SQLException e) {
            e.printStackTrace();
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", 500);
            errorMap.put("msg", "获取轮播图数据时出现错误");
            errorMap.put("data", null);

            resp.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = resp.getWriter();
            mapper.writeValue(writer, errorMap);
        }
    }
}

